import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { message, Table, Tag, Button, notification } from 'antd';
import { useRequest } from 'ahooks';
import { connect, NavLink, useNavigate } from 'umi';
import _ from 'lodash';
import type { NotificationPlacement } from 'antd/es/notification/interface';

// 发起网络请求，审核列表要显示的auditState!=0(_ne=0)【审核中1，已通过2，未通过3】,
// publishState<=1(发布状态小于等于1的【未发布 0】【待发布1】，publishState_lte=1）,
const getCurrentAuditListRequest = (userName: string) => {
    return axios.get(`http://localhost:3000/news?_expand=category&author=${userName}&auditState_ne=0&publishState_lte=1`)
};
// 发起网络请求，通过更新新闻信息
const updateNewsRequest = (item: any, id: string |number| undefined,formId:number) => {
    return axios.patch(`http://localhost:3000/news/${id}`, {
        ...item
    })
}
// 接口，定义类型
interface IStateObj {
    [key: string]: string
}

function AuditList(props: any) {
    // 跳转方法
    const navigate = useNavigate();
    // 从props解构出dispatch
    const { dispatch } = props;
    // useRequest - 获取当前用户的审核列表信息
    const { run: getCurrentAuditListData, loading: getCurrentNewsLoading } = useRequest(getCurrentAuditListRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            if (result.status === 200) {
                setNewsAuditList(result.data)
                console.log(result.data, params)
            }
        },
        onError(e, params) {
            message.warning('请求新闻数据失败')
        },
    })

    // useRequest - 更新当前id新闻信息
    const { run: UpdateCurrentNewsData, loading: updateLoading } = useRequest(updateNewsRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            if (result.status === 200) {
                // 更新审核列表信息
                getCurrentAuditListData(currentUser[0].username)
                openNotification('bottomRight', params[2]);
            }
        },
        onError(e, params) {
            message.warning('请求新闻数据失败')
        },
    })
    //从localStorage获取当前用户信息
    const currentUser = JSON.parse(localStorage.getItem('token') as string);
    // 存储新闻审核列表的数据
    const [newsAuditList, setNewsAuditList] = useState([])
    // 审核状态的数据对应的中文介绍
    const auditStateObj: IStateObj = {
        '0': '未审核',
        '1': '审核中',
        '2': '已通过',
        '3': '未通过'
    };
    const publishStateObj: IStateObj = {
        '0': '草稿箱',
        '1': '审核列表',
        '2': '【发布管理-已发布页面】',
        '3': '待发布'
    };
    // 审核状态的对应的按钮文字
    const buttonTextObj: IStateObj = {
        '1': '撤销',
        '2': '发布',
        '3': '修改'
    };
    // 审核状态的对应的标签组件的颜色
    const textColorObj: IStateObj = {
        '0': 'black',
        '1': 'orange',
        '2': 'green',
        '3': 'red'
    };
    const handelModifyNews = (item: any) => {
        console.log(item)
        const newItem = _.cloneDeep(item);
        switch (item.auditState) {
            case 1:
                // 撤销功能，将当前新闻的auditState从1->0；并更新审核列表的信息
                newItem.auditState = 0;
                UpdateCurrentNewsData(newItem, newItem.id,0);
                break;
            case 2:
                // 撤销功能，将当前新闻的publishState从1->2，添加更新时间的属性，取当前时间戳；并更新审核列表的信息
                newItem.publishState = 2;
                newItem.publishTime = Date.now();
                UpdateCurrentNewsData(newItem, newItem.id,2);
                if(!updateLoading){
                    navigate('/publish-manage/published');
                }
                break;
            case 3:
                // 更新功能，跳转到新闻更新页面
                dispatch({
                    type: 'StandBox/getCurrentNewsDetail',
                    payload: {
                        id: item.id,
                        navigate,
                        patchName: `/news-manage/update/${item.id}`
                    }
                })
                break;
            default:
                break;
        }
    };
    //#region 消息通知框
    const openNotification = (placement: NotificationPlacement, auditState: number) => {
        notification.open({
            message: `通知`,
            description: `你可以到${publishStateObj[auditState]}中查看您的新闻`,
            placement,
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    };
    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            key: 'title',
            render: (title: string, item: any) => {
                return <NavLink to={`/news-manage/preview/${item.id}`}>{title}</NavLink>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
            key: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            key: 'category',
            render: (category: any) => category.title
        },
        {
            title: '审核状态',
            dataIndex: 'auditState',
            key: 'auditState',
            render: (auditState: number) => {
                return <Tag color={textColorObj[auditState]}>{auditStateObj[auditState]}</Tag>;

            }
        },
        {
            title: '操作',
            render: (item: any) => {
                return (<div>
                    <Button type='primary' onClick={() => {
                        handelModifyNews(item)
                    }}>{buttonTextObj[item.auditState]}
                    </Button>

                </div>)
            }
        }
    ];
    useEffect(() => {
        // console.log(currentUser[0].username)
        getCurrentAuditListData(currentUser[0].username)
    }, [currentUser[0].username])
    return (
        <div>
            <Table dataSource={newsAuditList} columns={columns} 
            loading={updateLoading} rowKey={(item) => item.id} sticky scroll={{ y: '63vh' }}/>
        </div>
    )
}
const mapStateToProps = (state: any) => {
    return {
        currentNewsData: state.StandBox.currentNewsData,
    }
}
export default connect(mapStateToProps)(AuditList)